'use strict';
angular.module('gkwb')
    .controller('appCtrl', ['$scope', '$window', '$state', '$http', function($scope, $window, $state, $http) {
        $scope.app = {
            title: '2016年湖北省普通高考网上报名'
        }
        $scope.menus = [];
        $http.get('pages/menu.json')
            .success(function(data) {
                $scope.menus = data;
            })
        $scope.getUsername = function() {
            return $window.sessionStorage.groupName;
        }
        $scope.goHome = function(){
            var groupType = $window.sessionStorage.groupType;
            $state.go('dashboard.'+groupType);
        }
        $scope.logout = function() {
            delete $window.sessionStorage.groupName;
            delete $window.sessionStorage.groupId;
            delete $window.sessionStorage.groupType;
            $state.go('login');
        }
    }])
    .controller('DashboardCtrl', ['$scope', 'SignCard','$window','$http',function ($scope,SignCard,$window,$http) {
        var groupId = $window.sessionStorage.groupId;
        var groupType = $window.sessionStorage.groupType;
        $scope.loading = SignCard.query(groupId,groupType,false)
        .then(function(data){
            $scope.tasks = data;

        })

        $scope.sum = 0;
        $scope.labels = [];
        $scope.data = [[]];
        $scope.loadingMain = $http.get('/view/dashboard/'+groupType+'/'+groupId)
        .success(function(data){
            $scope.groups = data;
            var total = 0;
            angular.forEach(data,function(item){
                $scope.sum += item.signedCount;
                $scope.labels.push(item.groupName);
                $scope.data[0].push(item.signedCount);
            })
            
            
        })

        $scope.options = {
            animate: false,
            barColor: '#E67E22',
            scaleColor: false,
            lineWidth: 5,
            lineCap: 'butt'
        };

      $scope.series = ['Series A'];
      $scope.labels2 = ["文史", "艺术（文）", "理工", "艺术（理）", "体育（文）","体育（理）"];
  $scope.data2 = [65943, 21340, 83203, 11023,5432,14590];

  $scope.labels3 = ["11月18日", "11月19日", "11月20日", "11月21日", "11月22日", "11月23日", "11月24日"];
  $scope.data3 = [
    [13228, 3548, 540, 319, 786, 11127, 990]
  ];

        }])
    .controller('modifyPasswordCtrl', ['$scope', '$window', '$http', '$state', '$stateParams', function($scope, $window, $http, $state, $stateParams) {
        var userId = $window.sessionStorage.token;
        var oldPwd = $stateParams.pwd;
        $scope.pwd = {
            old: null,
            newPwd: null,
            newCheck: null
        }

        $scope.submitted = false;

        $scope.submit = function(form) {
            console.log($scope.pwd);
            if ($scope.pwd.newPwd !== $scope.pwd.newCheck) {
                alert('两次输入密码不一致！');
                $scope.pwd.newPwd = null;
                $scope.pwd.newCheck = null;
            }
            if (form.$invalid) {
                $scope.submitted = true;
                alert('有未填写项目或密码长度不够');
            } else {
                $http({
                        method: 'PUT',
                        url: '/api/studentuser/' + userId,
                        data: $scope.pwd.newPwd
                    })
                    .success(function(data) {
                        $state.go('main.promise');

                    })
                    .error(function(data, status) {

                    })
            }
        }
    }])
    .controller('SettingCtrl', ['$scope', '$http', 'toaster', function($scope, $http, toaster) {
        $scope.loading = $http.get('/view/settings')
        .success(function(data){
            $scope.settings = data;
        });

        $scope.save = function(){
            $scope.loading = $http.post('/view/settings',$scope.settings)
            .success(function(data){
                toaster.pop('success','保存成功');
            })
        }

    }])
    .controller('KSCtrl', ['$scope','Student', function ($scope,Student) {
        $scope.examId = null;
        $scope.subjects = [
            {id:2,name:'艺术(文)',objId:null},
            {id:5,name:'艺术(理)',objId:null}
        ]
        $scope.search = function(){
            $scope.loading = Student.getAll().then(function(data){
                $scope.students = data;
            })
        }
    }])
    .controller('OrderCtrl', ['$scope','Order', function ($scope,Order) {
        /**
        $scope.page = 0;
        $scope.examId = null;
        $scope.pageSize = 0;
        $scope.hasNext = true;

        function loadOrders(page,examId){
            var options = {
                page:page,
                size:10,
                examId:examId
            }
            $scope.loading = Order.query(options,examId)
            .then(function(data){
                $scope.orders = data.list;
                var c = data.count%options.size;
                var pageSize = parseInt(data.count/options.size);
                $scope.pageSize = c == 0?pageSize:pageSize+1;
            });
        }
        $scope.search = function(){
            $scope.page = 0;
            loadOrders(0,$scope.examId);
        }
        $scope.pageNext = function(){
            $scope.page++;
            loadOrders($scope.page,$scope.examId);
        }
        $scope.pagePrev = function(){
            if($scope.page > 0){
                $scope.page--;
                loadOrders($scope.page,$scope.examId);
            }
        }
        */
        $scope.search = function(examId){
            $scope.loading = Order.query(examId)
            .then(function(data){
                $scope.orders = data;
            })
        }
    }])
    //报名卡管理
    .controller('SignCardCtrl', ['$scope','Dict','$window','$http','SignCard','$state', function ($scope,Dict,$window,$http,SignCard,$state) {
        var groupId = $window.sessionStorage.groupId;
        $scope.examTypes = Dict.query({type:'examtype'});
        $scope.sc = {
            periodType:'CURRENT',
            signPointId:groupId
        };
        $scope.loadSubjects = function(){
            $scope.subjects = Dict.query({type:'subject',parentId:$scope.sc.examTypeId});
        }

        $scope.create = function(){
            $scope.loading = SignCard.create($scope.sc)
            .then(function(data){
                alert('申请成功');
                $state.go('sc.list');
            },function(err){
                alert(err.message);
            })
        }
    }])
    .controller('SignCardListCtrl', ['$scope','SignCard','$window','$modal','toaster','$filter', function ($scope,SignCard,$window,$modal,toaster,$filter) {

        var groupId = $window.sessionStorage.groupId;
        var groupType = $scope.groupType = $window.sessionStorage.groupType;
        $scope.loading = SignCard.query(groupId,groupType)
            .then(function(data){
                
                var copy = [];
                angular.copy(data,copy);
                $scope.signCards = data;
                var sps = _.pluck(copy,'signPoint');
                $scope.signPoints = [];
                var ids = [];
                angular.forEach(sps,function(s){
                    if(ids.indexOf(s.id) == -1){
                        $scope.signPoints.push(s);
                        ids.push(s.id);
                    }
                })
            },function(err){
                alert(err.message);
            })
        
        $scope.getSum = function(){
            $filter('filter')($scope.signCards, $scope.search);
            var sum =  _.reduce($scope.signCards, function(memo, num){ return memo + num.totalCount; }, 0);
            return sum;
        }

        $scope.generate = function(record){
            var f = $window.confirm('确定生成报名卡？');
            if(f){
                $scope.loading = SignCard.generate(record.id)
                .then(function(data){
                    record.startIndex = data.startIndex;
                    record.endIndex = data.endIndex;
                    record.createdTime = data.createdTime;
                    record.created = true;
                    var msg = data.signPoint.groupName + ' ' + data.examType.name + data.subject.name;
                    toaster.pop('success',msg,'成功生成'+data.totalCount+'份报名卡');
                },function(err){
                    alert(err.message);
                })
            }
        }

        $scope.remove = function(index){
            var record = $scope.signCards[index];
            var msg = '是否确定删除'+record.signPoint.groupName + ' ' + record.examType.name + record.subject.name
                + '的报名卡申报？';
            var f = $window.confirm(msg);
            if(f){
                $scope.loading = SignCard.remove(record.id)
                .then(function(data){
                    $scope.signCards.splice(index,1);
                    toaster.pop('success','删除成功');
                },function(err){
                    alert(err.message);
                })
            }
        }

        var modal = $modal({scope: $scope, templateUrl: 'tpl/modal.print.html', show: false});
          $scope.print = function(item) {
            $scope.printItem = {};
            angular.copy(item,$scope.printItem);
            $scope.printItem.start  = parseInt($scope.printItem.startIndex);
            $scope.printItem.min = parseInt($scope.printItem.startIndex);
            modal.$promise.then(modal.show);
          };
        
    }])
    .controller('HomeCtrl', ['$scope', '$http', function($scope, $http) {
        $scope.menus = [];
        $http.get('pages/menu.json')
            .success(function(data) {
                $scope.menus = data;
            })
    }]);